package setting

import (
	"fmt"
	"github.com/spf13/cast"
	"github.com/spf13/viper"
	"time"
)

type IniApp struct {
	AppName  string
	App      App
	Server   Server
	Database Database
	Redis    Redis
}

type App struct {
	JwtSecret string
	PageSize  int
	PrefixUrl string

	RuntimeRootPath string

	FileSavePath   string
	ImageMaxSize   int
	ImageAllowExts []string

	ExportSavePath string
	QrCodeSavePath string
	FontSavePath   string

	LogSavePath string
	LogSaveName string
	LogFileExt  string
	TimeFormat  string

	MerchantPath string
	AgentPath    string
}

//var AppSetting = &App{}

type Server struct {
	RunMode      string
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

//var ServerSetting = &Server{}

type Database struct {
	Type        string
	User        string
	Password    string
	Host        string
	Name        string
	Port        int
	TablePrefix string
}

//var DatabaseSetting = &Database{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var c IniApp

//var RedisSetting = &Redis{}

//var cfg *ini.File

// Setup initialize the configuration instance
func Setup() {

	// 设置文件名
	viper.SetConfigName("app")
	// 设置文件类型
	viper.SetConfigType("ini")
	// 设置文件路径，可以多个viper会根据设置顺序依次查找
	viper.AddConfigPath(".")
	viper.AutomaticEnv()
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %s", err))
	}

	err = viper.Unmarshal(&c)
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %s", err))
	}
}

// GetTempMerchantPath 返回临时商户文件夹路径
func (i *IniApp) GetTempMerchantPath(userId interface{}) string {
	return i.App.RuntimeRootPath + "temp/" + i.App.MerchantPath + cast.ToString(userId) + "/"
}

// GetUserMerchantPath 返回临时商户文件夹路径
func (i *IniApp) GetUserMerchantPath(userId interface{}) string {
	return i.App.RuntimeRootPath + "user/" + i.App.MerchantPath + cast.ToString(userId) + "/"
}

// GetUserAgentPath 返回代理商文件夹路径
func (i *IniApp) GetUserAgentPath(userId interface{}) string {
	return i.App.RuntimeRootPath + i.App.AgentPath + cast.ToString(userId) + "/"
}

//// mapTo map section
//func mapTo(section string, v interface{}) {
//	err := cfg.Section(section).MapTo(v)
//	if err != nil {
//		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
//	}
//}

func GetConfig() *IniApp {
	return &c
}
